import { app } from 'electron'
import path from 'path'
import winston from 'winston'
import fs from 'fs'

// 确保日志目录存在
const logDir = path.join(app.getPath('userData'), 'logs')
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true })
}

// 创建结构化日志服务
export const logger = winston.createLogger({
  level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
  format: winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  defaultMeta: {
    service: 'spf-electron',
    version: app.getVersion(),
    platform: process.platform,
    arch: process.arch
  },
  transports: [
    // 错误日志文件
    new winston.transports.File({
      filename: path.join(logDir, 'error.log'),
      level: 'error',
      maxsize: 5242880, // 5MB
      maxFiles: 5,
      tailable: true
    }),
    // 综合日志文件
    new winston.transports.File({
      filename: path.join(logDir, 'combined.log'),
      maxsize: 5242880, // 5MB
      maxFiles: 5,
      tailable: true
    })
  ],
  // 异常处理
  exceptionHandlers: [
    new winston.transports.File({
      filename: path.join(logDir, 'exceptions.log')
    })
  ],
  // 拒绝处理
  rejectionHandlers: [
    new winston.transports.File({
      filename: path.join(logDir, 'rejections.log')
    })
  ]
})

// 开发环境下同时输出到控制台
if (process.env.NODE_ENV === 'development') {
  logger.add(new winston.transports.Console({
    format: winston.format.combine(
      winston.format.colorize(),
      winston.format.timestamp({
        format: 'HH:mm:ss'
      }),
      winston.format.printf(({ timestamp, level, message, service, ...meta }) => {
        const metaStr = Object.keys(meta).length ? JSON.stringify(meta, null, 2) : ''
        return `${timestamp} [${service}] ${level}: ${message} ${metaStr}`
      })
    )
  }))
}

// 导出便捷的日志方法
export const log = {
  error: (message: string, meta?: any) => logger.error(message, meta),
  warn: (message: string, meta?: any) => logger.warn(message, meta),
  info: (message: string, meta?: any) => logger.info(message, meta),
  debug: (message: string, meta?: any) => logger.debug(message, meta),
  
  // 性能日志
  performance: (operation: string, duration: number, meta?: any) => {
    logger.info(`Performance: ${operation}`, {
      duration,
      operation,
      type: 'performance',
      ...meta
    })
  },
  
  // 数据库操作日志
  database: (operation: string, table?: string, meta?: any) => {
    logger.debug(`Database: ${operation}`, {
      operation,
      table,
      type: 'database',
      ...meta
    })
  },
  
  // IPC通信日志
  ipc: (channel: string, direction: 'send' | 'receive', meta?: any) => {
    logger.debug(`IPC: ${direction} ${channel}`, {
      channel,
      direction,
      type: 'ipc',
      ...meta
    })
  }
}

// 导出默认logger
export default logger
